package com.test.publicmethod;
import org.dom4j.*;
import org.testng.annotations.Test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;

public class GetServiceIP {


    public String getIP(String env, String service) {
        try {
            URL url;
            if (env == "stage") {
                url = new URL("http://10.157.24.76:1111/eureka/apps");
            } else {
                url = new URL("http://10.157.46.143:1111/eureka/apps");
            }
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStreamReader input = new InputStreamReader(connection.getInputStream(), "utf-8");
            BufferedReader reader = new BufferedReader(input);
            String line = "";
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
            }
            String xmlStr = stringBuffer.toString();
            Document document = null;
            try {
                document = DocumentHelper.parseText(xmlStr);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            String ip = "";
            Element root = document.getRootElement();
            for (Iterator iterator = root.elementIterator(); iterator.hasNext(); ) {
                Element type = (Element) iterator.next();
                String serviceName = type.elementText("name");
                if (serviceName != null && serviceName.equals(service)) {
                    ip = type.element("instance").elementText("hostName") + ":" + type.element("instance").elementText("port");
                }
            }

            String IpValue="http://"+ip;
            return IpValue;
        }catch (Exception e){
            System.out.println(e.toString());
            return "0";

        }
    }

    @Test
    public void ff(){

        String Ip=getIP("stage","MYACCOUNT-SERVICE");
        System.out.println(Ip);
    }
}
